#!/bin/bash

ARG_COUNT=$#  # 获取传入参数的个数
PRO_NAME="appRPIUI"  # 项目名称
BUILD_PATH="build"  # 默认构建路径

# 如果传入参数是 1，则使用 build_x86 作为构建路径
if [ $ARG_COUNT -eq 1 ]; then
    BUILD_PATH="build_x86"
fi

# 检查构建路径是否存在，如果不存在则创建
if [ ! -d $BUILD_PATH ]; then
     mkdir $BUILD_PATH
fi

# 删除构建路径下的所有文件
#rm -rf ./$BUILD_PATH/*

# 切换到构建目录
cd ./$BUILD_PATH

# 检查 CMake 配置是否已存在，并且配置没有改变
CMAKE_CACHE="$BUILD_PATH/CMakeCache.txt"

if [ ! -f $CMAKE_CACHE ]; then
    # 如果没有 CMake 缓存，说明第一次运行 CMake 配置
    echo "Configuring project with CMake..."
    if [ $ARG_COUNT -eq 0 ]; then
        cmake .. -DCMAKE_TOOLCHAIN_FILE=/home/ding/qt6/pi/lib/cmake/Qt6/qt.toolchain.cmake -DCMAKE_BUILD_TYPE=Debug
    elif [ $ARG_COUNT -eq 1 ]; then
        cmake .. -DQt6_DIR=/home/ding/qt6/host/lib/cmake/Qt6
    else 
        echo "Unknown args"
        exit 1
    fi
    if [ $? -ne 0 ]; then
        echo "CMake configuration failed. Please check the output for errors."
        exit 1
    fi
else
    # 如果 CMake 配置已经存在，检查配置是否有变化
    echo "CMake configuration already exists, skipping reconfiguration."
fi

# 使用 make 构建项目
make -j4

if [ $? -ne 0 ]; then
    echo "Build failed. Please check the output for errors."
    exit 1
fi

echo "Build successful!"

# 如果传入参数为 1，直接运行构建的程序
if [ $ARG_COUNT -eq 1 ]; then
    ./$PRO_NAME
    exit 0
fi

# 将构建好的程序通过 scp 复制到远程主机
scp ./$PRO_NAME ding@192.168.18.40:/home/ding

if [ $? -ne 0 ]; then
    echo "scp failed. Please check the output for errors."
    exit 1
fi

echo "scp successful"
